<?php
    function getConfig($file){
        $config = file_get_contents($file);
        $json = json_decode($config, true);
        return $json;
    }
    
    function packageToFile($package){
        $filename = str_replace("rhy.", "src.", trim($package));
        $filename = str_replace(".","\\", $filename);
        $filename = dirname(__FILE__)."\\".$filename.".rhy.js";
        
        return $filename;
    }
    
    function getDependencies($package, $current){
        $content = file_get_contents(packageToFile($package));
        
        $matches = array();
        
        if(preg_match("#.* @dependencies (.*)#", $content, $matches) == 0)
                return;
        
        $dependencies = $matches[1];
        $dependencies = explode(",", $dependencies);
        
        
        
        foreach($dependencies as $key => $dependency){
            $dependencies[$key] = trim($dependency);
        }
        
        
        
        $result = $dependencies;
        
        foreach($dependencies as $dependency){
           if(!in_array($dependency, $current)){
               $current = array_unique(array_merge($current, array($dependency)));
               $new = getDependencies($dependency, $current);
               if($new != null)
                   $result = array_merge($result, $new);
           }
        }
        
        return array_unique($result);
    }
    
    if(count($argv) == 1){
        echo "\nERROR - You must specify a configuration file.\n";
        die();
    }
 
    $config = getConfig($argv[1]);
    $packages = array();
    
    foreach($config['files'] as $package){
        $deps = getDependencies($package, $packages);
        
        if($deps != null)
            $packages = array_merge($packages, $deps);
        $packages = array_unique($packages);
    }
    
        $packages = array_merge($packages, $config['files']);
        $packages = array_unique($packages);
    
    echo "\nCOMPLETE - Generated following content: \n";
    print_r($packages);
        
    
    $rawBegin = file_get_contents(dirname(__FILE__)."\\src\\rhy.js");
    $rawCore  = "";
    $rawExtra = "";
    $rawEnding = "";
    
    foreach($packages as $file){
       $code = file_get_contents(packageToFile($file));
       
       if(preg_match("#.* @ending.*#", $code) > 0){
            $rawEnding .= $code;
       }
       else if(strpos($file, ".core.") !== FALSE){
            $rawCore .= $code; 
       }
       else{
            $rawExtra .= $code;    
       }
    }
    
    $rawCode = $rawBegin.$rawCore.$rawExtra.$rawEnding;
    
    file_put_contents(dirname(__FILE__)."\\build\\rhy.".$config['name'].".js", $rawCode);
    
    exec("java -jar yuicompressor.jar -o build\\rhy.".$config['name'].".min.js      build\\rhy.".$config['name'].".js");
?>